<!-- 登录页面 -->
<template>
  <!-- <navbar btn-background="bg-gradient-success" /> -->
  <nav
    class="top-0 navbar navbar-expand-lg position-absolute z-index-3 shadow-none my-2 navbar-transparent w-100"
  >
    <div class="container">
      <img
        :src="require('@/assets/img/curved-images/signalLogo.png')"
        style="width: 186px; height: 32px"
        alt=""
      />
      <div class="pt-3 pb-2 collapse navbar-collapse w-100 py-lg-0">
        <ul class="navbar-nav d-lg-block d-none" style="margin-left: auto">
          <li class="nav-item">
            <soft-button
              class="mb-0 btn btn-sm btn-round me-1"
              color="info"
              variant="gradient"
              @click="openModal"
              >Subscribe Now</soft-button
            >
          </li>
        </ul>
      </div>
    </div>
  </nav>
  <div
    class="pt-5 m-3 page-header align-items-start min-vh-50 pb-11 border-radius-lg"
    :style="{
      backgroundImage:
        'url(' + require('@/assets/img/curved-images/loginBg.png') + ')',
    }"
  >
    <span class="mask bg-gradient-dark opacity-6"></span>
    <div class="container">
      <div class="row justify-content-center">
        <div class="mx-auto text-center col-lg-5">
          <h1 class="mt-5 mb-2 text-white">Welcome Back!</h1>
          <!-- <p class="text-white text-lead">
              Use these awesome forms to login or create new account in your
              project for free.
            </p> -->
        </div>
      </div>
    </div>
  </div>
  <div class="container">
    <div class="row mt-lg-n10 mt-md-n11 mt-n10 justify-content-center">
      <div class="mx-auto col-xl-4 col-lg-5 col-md-7">
        <div class="card z-index-0">
          <div class="pt-4 text-center card-header">
            <h5>Sign in</h5>
          </div>
          <div
            class="px-3 row px-xl-5 px-sm-4 flex mx-0 justify-content-center"
          >
            <div
              class="btn btn-outline-light flex justify-content-center py-0"
              style="width: 74px; height: 58px; line-height: 58px"
            >
              <img
                :src="require('@/assets/icon/metamaskLogo.png')"
                class="avatar-xs"
                alt=""
              />
            </div>
          </div>
          <div class="card-body">
            <div class="mb-3">
              <input
                v-model="email"
                type="text"
                class="form-control"
                :class="{ 'is-invalid': emailFailed }"
                placeholder="Email"
                onKeyUp="value=value.replace(/[\u4e00-\u9fa5]/ig,'')"
                @blur="email_blur"
              />
              <p v-if="emailFailed" class="text-danger text-xs mt-1">
                <!-- 请输入正确的邮箱地址 -->
                {{ "Please enter the correct email address" }}
              </p>
            </div>
            <div class="mb-3" style="position: relative">
              <input
                v-model="code"
                type="text"
                class="form-control"
                :class="{ 'is-invalid': codeFailed }"
                placeholder="Verification code"
                @keyup="limitCodeLength"
              />
              <button
                :style="{ color: sendCodeStatus ? '#A2A5B0' : '#344767' }"
                class="sendCodeBtn"
                :disabled="sendCodeStatus"
                @click="sendCodeEvent"
              >
                {{ sendCodeText }}
              </button>
              <p v-if="codeFailed" class="text-danger text-xs">
                {{ codeError }}
              </p>
            </div>
            <div class="text-center">
              <soft-button
                class="my-4 mb-2"
                variant="gradient"
                color="info"
                full-width
                @click="loginEvent"
                >Sign in
              </soft-button>
            </div>
            <div class="mb-2 text-center position-relative">
              <p
                class="px-3 mb-2 text-sm bg-white font-weight-bold text-secondary text-border d-inline z-index-2"
              >
                or
              </p>
            </div>
            <div class="text-center">
              <soft-button
                class="mt-2 mb-4"
                variant="gradient"
                color="dark"
                full-width
                @click="openModal"
                >Subscribe
              </soft-button>
            </div>
            <div class="text-xs text-center text-secondary">
              If you are not a subscriber to Tradingsignal.ai. Please sign up
              for our Free/Premium to log in to Tradingsignal.ai.
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="position-fixed bottom-1 end-1 z-index-2">
      <soft-snackbar
        v-if="snackbar"
        title="You are not a subscriber"
        date=""
        description="You are not a subscriber to Tradingsignal.ai. Please sign up for our Free/Premium to log in to Tradingsignal.ai."
        :icon="{ component: 'ni ni-check-bold', color: 'danger' }"
        color="white"
        :close-handler="closeSnackbar"
      />
    </div>
    <BuyMealModal ref="buyMealModalRef" />
  </div>
</template>

<script>
// import Navbar from "@/examples/PageLayout/Navbar.vue";
// import SoftInput from "@/components/SoftInput.vue";
// import SoftSwitch from "@/components/SoftSwitch.vue";
import SoftButton from "@/components/SoftButton.vue";
import { sendEmail, emailLogin } from "@/request/api.js";
import SoftSnackbar from "@/components/SoftSnackbar.vue";
import BuyMealModal from "@/components/BuyMealModal.vue";
import { mapMutations } from "vuex";
export default {
  name: "SigninBasic",
  components: {
    // Navbar,
    // SoftInput,
    // SoftSwitch,
    SoftButton,
    SoftSnackbar,
    BuyMealModal,
  },
  data() {
    return {
      email: "",
      emailFailed: false, //邮箱地址错误
      codeFailed: false, //验证码错误
      codeError: "code error", //验证码错误文案
      countdown: 10, //邮箱验证码读秒
      sendCodeText: "Send",
      sendCodeStatus: true,
      code: "", //验证码
      snackbar: false,
    };
  },
  watch: {
    email(val) {
      const emailPattern = /^([A-Za-z0-9_.-])+@([A-Za-z0-9_.-])+\.[A-Za-z]{2,4}$/;

      if (emailPattern.test(val)) {
        this.emailFailed = false;
        this.sendCodeStatus = false;
      } else {
        this.sendCodeStatus = true;
      }
    },
    code() {
      this.codeFailed = false;
    },
  },
  created() {
    this.toggleEveryDisplay();
    this.toggleHideConfig();
  },
  beforeUnmount() {
    this.toggleEveryDisplay();
    this.toggleHideConfig();
  },
  methods: {
    ...mapMutations(["toggleEveryDisplay", "toggleHideConfig"]),
    openModal() {
      this.$refs.buyMealModalRef.dialogVisible = true;
    },
    closeSnackbar() {
      this.snackbar = false;
    },
    // 登录
    async loginEvent() {
      if (!this.email) {
        this.emailFailed = true;
      } else {
        this.emailFailed = false;
      }
      if (!this.code) {
        this.codeFailed = true;
      } else {
        this.codeFailed = false;
      }
      const submit = async () => {
        const params = {
          email: this.email,
          code: this.code,
        };
        const res = await emailLogin(params);
        // console.log(res);
        if (res.code == 400) {
          this.snackbar = true;
          return;
        } else if (res.code == 0) {
          //
          this.codeFailed = true;
          return;
        } else {
          this.$store.commit("app/upToken", res.data.token);
          await this.$store.dispatch("app/setAccount");
          this.$router.push("/projects");
        }
      };
      !this.emailFailed && !this.codeFailed && submit();
    },
    // 限制数量
    limitCodeLength() {
      if (this.code.length > 4) {
        this.code = this.code.slice(0, 4);
      }
    },
    //发送短信验证码
    async sendCodeEvent() {
      // e.preventDefault();
      const sendMsg = {
        email: this.email,
        event: "login",
      };

      await sendEmail(sendMsg).then((res) => {
        if (res.code != 200) {
          this.$message({
            type: "error",
            message: res.msg,
          });
          return;
        }
        this.$message({
          type: "success",
          message: "verification code is sent successfully",
        });
        let settime = setInterval(() => {
          if (this.countdown == 0) {
            //发送验证码
            this.sendCodeText = "Resend";
            this.countdown = 10;
            this.sendCodeStatus = false;
            clearInterval(settime);
            return false;
          } else {
            this.sendCodeStatus = true;
            this.sendCodeText = this.countdown + "s";
            this.countdown--;
          }
        }, 1000);
      });
    },
    //邮箱验证
    email_blur() {
      if (!this.email) {
        // 值为空就return
        return;
      }
      //   console.log(this.email,verify.test(this.email));
      let verify = /^\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/;
      if (!verify.test(this.email)) {
        this.emailFailed = true;
      } else {
        this.emailFailed = false;
      }
    },
  },
};
</script>
<style scoped lang="scss">
.sendCodeBtn {
  position: absolute;
  right: 12px;
  top: 10px;
  outline: none;
  font-size: 14px;
  padding: 0px;
  border: 0;
  background: #fff;
}
</style>
